package com.piece.core.log.logback;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import com.piece.core.log.support.socket.LoggerMessage;
import com.piece.core.log.support.socket.LoggerQueue;
import java.sql.Date;
import java.text.DateFormat;

public class ProcessLogFilter extends Filter<ILoggingEvent> {

    Level level;

    @Override
    public FilterReply decide(ILoggingEvent event) {
        if (event.getLevel().levelInt < this.level.levelInt) {
            return FilterReply.NEUTRAL;
        }

        String exception = "";
        IThrowableProxy iThrowableProxy = event.getThrowableProxy();
        if (null != iThrowableProxy) {
            exception = "<span class='red'>" + iThrowableProxy.getClassName() + " " + iThrowableProxy.getMessage() + "</span></br>";
            for (int i = 0; i < iThrowableProxy.getStackTraceElementProxyArray().length; i++) {
                exception += "<span class='red'>" + iThrowableProxy.getStackTraceElementProxyArray()[i].toString() + "</span></br>";
            }
        }

        LoggerMessage loggerMessage = new LoggerMessage(
                event.getMessage(),
                DateFormat.getDateTimeInstance().format(new Date(event.getTimeStamp())),
                event.getThreadName(),
                event.getLoggerName(),
                event.getLevel().levelStr,
                exception,
                ""
        );

        LoggerQueue.getInstance().push(loggerMessage);
        return FilterReply.ACCEPT;
    }

    public void setLevel(Level level) {
        this.level = level;
    }
}
